package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserVerifyRequest;
import com.cskaoyan.user.dto.UserVerifyResponse;
import com.cskaoyan.user.service.UserVerifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * 类说明
 *
 * @author zhangfuqiang
 * @date 2022/5/19
 */
@Service
public class UserVerifyServiceImpl implements UserVerifyService {

    @Autowired
    UserVerifyMapper userVerifyMapper;
    @Autowired
    MemberMapper memberMapper;

    @Override
    public UserVerifyResponse userVerify(UserVerifyRequest userVerifyRequest) {
        UserVerifyResponse userVerifyResponse = new UserVerifyResponse();
        String userName = userVerifyRequest.getUserName();
        String uuid = userVerifyRequest.getUuid();

        try {
            //根据用户名和UUID匹配用户，匹配到则更改激活状态为true
            Example example = new Example(UserVerify.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("username",userName);
            criteria.andEqualTo("uuid",uuid);
            List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example);

            if(userVerifies.size() == 1){
                //修改用户认证表
                UserVerify userVerify = userVerifies.get(0);
                userVerify.setIsVerify("Y");
                userVerifyMapper.updateByPrimaryKeySelective(userVerify);
                //修改用户表
                Member member = new Member();
                member.setIsVerified("Y");
                member.setUpdated(new Date());
                Example example2 = new Example(Member.class);
                example2.createCriteria().andEqualTo("username",userVerify.getUsername());
                memberMapper.updateByExampleSelective(member, example2);

                userVerifyResponse.setCode(UserRetCode.SUCCESS.getCode());
                userVerifyResponse.setMsg(UserRetCode.SUCCESS.getMessage());
            }else {
                userVerifyResponse.setCode(UserRetCode.DATA_NOT_EXIST.getCode());
                userVerifyResponse.setMsg(UserRetCode.DATA_NOT_EXIST.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(userVerifyResponse, e);
        }

        return userVerifyResponse;
    }
}
